//
//  WaitHandleList.m
//  OASystem
//
//  Created by mac on 14-5-6.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "WaitHandleList.h"

@interface WaitHandleList ()

@end

@implementation WaitHandleList

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self getNetData];
}

//返回上一级
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initNavi
{
    //初始化UINavigation
    self.navigationItem.titleView = [[UIView alloc] initWithFrame:CGRectMake(110, 0, 100, 44)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.text = @"待办事宜";
    titleLabel.font = HEIGHT_FONT(18.0f);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    [self.navigationItem.titleView addSubview:titleLabel];
    
    //添加导航又边用户信息
    //初始化UINavigation左按钮
    UIButton *helloButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 80, 24)];
    [helloButton setTitle:[NSString stringWithFormat:@"你好，%@",USER_NICK_NAME] forState:UIControlStateNormal];
    helloButton.titleLabel.font = HEIGHT_FONT(13.0f);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:helloButton];
    
    //初始化UINavigation左按钮
    UIButton *naviButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 45, 24)];
    [naviButton setTitle:@"返回" forState:UIControlStateNormal];
    naviButton.titleLabel.font = HEIGHT_FONT(13.0f);
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_n.png"] forState:UIControlStateNormal];
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_p.png"] forState:UIControlStateHighlighted];
    [naviButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:naviButton];
}

- (void)getNetData
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if(!listArr)
            listArr = [[NSMutableArray alloc] init];
        listArr = [[[SendHttpOperation shareSendHttpOperation] WaitHandleBanli:TEMP_USERNAME] objectForKey:@"info"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
            if (listArr.count != 0)
            {
                NSMutableArray *tempArr = [[NSMutableArray alloc] init];
                for (int i = 0; i<listArr.count; i++)//筛选数据
                {
                    NSDictionary *temp = [listArr objectAtIndex:i];
                    NSString *originStr = [temp objectForKey:@"title"];
                    if([originStr hasPrefix:@"【编号】"]||[originStr hasPrefix:@"【归档】"]||[originStr hasPrefix:@"【清稿打印】"])
                        [tempArr addObject:temp];
                }
                [listArr removeObjectsInArray:tempArr];
            }
            [waitHandletable reloadData];
        });
    });
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //UITableView分割线去掉
    waitHandletable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    [self getNetData];
    
    [self initNavi];
    [self pullRefresh];
}

#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [listArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WaitHandleCustomCell* cell = (WaitHandleCustomCell*)[tableView dequeueReusableCellWithIdentifier:@"WaitHandleCustomCell"];
    if (cell == nil)
    {
        NSArray* arry = [[NSBundle mainBundle] loadNibNamed:@"WaitHandleCustomCell" owner:nil options:nil];
        cell = [arry objectAtIndex:0];
    }
    
    //自定义分割线
    UIImageView *line    = [[UIImageView alloc] initWithFrame:CGRectMake(0, 59, 320, 1)];
    line.backgroundColor = NOTICEBOARD_LINE_COLOR;
    [cell.contentView addSubview:line];
    
    //添加数据
    NSString *titleStr  = [NSString stringWithFormat:@"%@",[[listArr objectAtIndex:indexPath.row] objectForKey:@"title"]];//@"这只是测试使用的东东啊";
    NSString *handleStr = [NSString stringWithFormat:@"%@",[[listArr objectAtIndex:indexPath.row] objectForKey:@"handler"]];//@"你好，李四";
    NSString *submitStr = [NSString stringWithFormat:@"%@",[[listArr objectAtIndex:indexPath.row] objectForKey:@"submitter"]];//@"你好，李四";
    NSString *time      = [NSString stringWithFormat:@"%@",[[listArr objectAtIndex:indexPath.row] objectForKey:@"sendTime"]];//@"2014/04/15";
    
    cell.title.text     = [NSString stringWithFormat:@"%@",titleStr];
    cell.handle.text    = [NSString stringWithFormat:@"%@",handleStr];
    cell.author.text    = [NSString stringWithFormat:@"%@",submitStr];
    cell.time.text      = [NSString stringWithFormat:@"%@",time];
    //    cell.image.image    = [UIImage  imageNamed:@"ggl_new.png"];
    
    cell.contentView.backgroundColor = NOTICEBOARD_BACKCOLOR;
    cell.selectionStyle              = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *param1 = [[listArr objectAtIndex:indexPath.row] objectForKey:@"ProcessVersionInstanceGuid"];
        NSString *param2 = [[listArr objectAtIndex:indexPath.row] objectForKey:@"WorkItemGuid"];
        NSString *param3 = [[listArr objectAtIndex:indexPath.row] objectForKey:@"MessageItemGuid"];

        NSDictionary *dic = [[SendHttpOperation shareSendHttpOperation] Handle_Main:TEMP_USERNAME
                                                         ProcessVersionInstanceGuid:param1
                                                                       WorkItemGuid:param2
                                                                    MessageItemGuid:param3];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
            if ([[dic objectForKey:@"errcode"] isEqualToString:@"0"])
            {
                //push到展示界面
                DisplayWaitHandleView *instance = [[DisplayWaitHandleView alloc] init];
                instance.displayHandleDic = [dic objectForKey:@"info"];
                instance.workItemGuidStr = param2;
                [self.navigationController pushViewController:instance animated:YES];
            }
            else
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":([[dic objectForKey:@"errcode"]intValue]==1?@"获取数据失败":@"用户身份验证失败")}];
        });
    });
}

#pragma mark 重新加载下拉框
- (void)pullRefresh
{
    if(_refreshHeaderView)
    {
        [_refreshHeaderView removeFromSuperview];
    }
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)];
    _refreshHeaderView.delegate = self;
    [waitHandletable addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
}

#pragma mark EGORefreshTableHeaderDelegate(上下下拉操作)
- (void)reloadTableViewDataSource
{
	product_reloading = YES;
	NSLog(@"开始获取更多数据...");
	//打开线程，加载更多数据
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if(!listArr)
            listArr = [[NSMutableArray alloc] init];
        listArr = [[[SendHttpOperation shareSendHttpOperation] WaitHandleBanli:TEMP_USERNAME] objectForKey:@"info"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (listArr.count != 0)
            {
                NSMutableArray *tempArr = [[NSMutableArray alloc] init];
                for (int i = 0; i<listArr.count; i++)//筛选数据
                {
                    NSDictionary *temp = [listArr objectAtIndex:i];
                    NSString *originStr = [temp objectForKey:@"title"];
                    if([originStr hasPrefix:@"【编号】"]||[originStr hasPrefix:@"【归档】"]||[originStr hasPrefix:@"【清稿打印】"])
                        [tempArr addObject:temp];
                }
                [listArr removeObjectsInArray:tempArr];
                
                [waitHandletable reloadData];
            }
            [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
        });
    });
}

- (void)doneLoadingTableViewData
{
    NSLog(@"加载更多结束");
    [self pullRefresh];
	product_reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:waitHandletable];
}

#pragma mark UIScrollViewDelegate(上拉下拉判断)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:waitHandletable];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:waitHandletable];
}


#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
	return product_reloading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	return [NSDate date];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
